package com.ebs.md.container.esper;

/**
 * Perforce Revision:
 *  $File: //depot/MarketData/fxmonitor/main/src/main/java/com/ebs/md/container/esper/EsperStarter.java $
 *  $Revision: #9 $  $Change: 115350 $  $DateTime: 2012/10/03 12:17:26 $  $Author: Arik.Sher $
 */

import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.springframework.util.Assert;

import com.espertech.esper.client.Configuration;
import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPRuntime;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;

/**
 * 
 */
public class EsperStarter
implements  IEsperAccessor
           ,IEsperAdminAccessor
{
	/**
	 * map between eventTypeName and eventClassName
	 * 
	 * @see Configuration#addEventType(String, String) 
	 */
	protected Map<String, String> eventTypesMap;
	protected String              engineName;
	protected Set<AlertGroup>     alertGroups; // can be null, so could test easily
	
	protected Configuration     epConfig;
	protected EPServiceProvider epSP;
	
	/**
	 * 
	 * use when the prepareStatements will be called later after CCC config is ready.
	 */
	public void init() {
		Assert.hasText(engineName, "'engineName' should contain text");
//		Assert.notEmpty(alertGroups, "'alertGroups' should not be empty");
		
		initEsperConfig();
		
		epSP = EPServiceProviderManager.getProvider(engineName, epConfig);
	}
	
	/**
	 * 
	 * can be used with tests where do not work with CCC
	 */
	public void start() {
		init();
		prepareAlertGroups();
	}
	
	public void setAlertGroups(Set<AlertGroup> alertGroups) {
		this.alertGroups = alertGroups;
	}
	
	public void setEventTypesMap(Map<String, String> eventTypesMap) {
		this.eventTypesMap = eventTypesMap;
	}

	public void setEngineName(String engineName) {
		this.engineName = engineName;
	}

	protected void initEsperConfig() {
		epConfig = new Configuration();
		
		if ( eventTypesMap != null ) {
			for ( Entry<String, String> currEntry : eventTypesMap.entrySet() ) {
				epConfig.addEventType(currEntry.getKey(), currEntry.getValue());
			}
		}
	}
	
	protected void prepareAlertGroups() {
		if ( alertGroups != null ) {
			EPAdministrator epAdministrator = epSP.getEPAdministrator();
			
			for ( AlertGroup curr : alertGroups ) {
				curr.prepare(epAdministrator);
			}
		}
	}
	
	public EPRuntime getEPRuntime() {
		return epSP.getEPRuntime();
	}

	public EPAdministrator getEPAdministrator() {
		return epSP.getEPAdministrator();
	}

}
